import {
  lget,
  lset,
  lremoveall
} from '@/utils/storage'
import {
  getToken
} from '@/utils/getToken'

import {
  GetLoginUserInfo
} from '@/api/login'
import {
  GetLoginUserPermissionList
} from '@/api/system'
import {
  GetLogisticsList
} from '@/api/order'

import permissionRoutes from '../../router/permissionRoutes'

const getWhiteList = () => {
  let arr = []
  permissionRoutes.forEach(item => {
    if (item.meta && item.meta.isWhiteList) {
      arr.push(item.name)
    }
    if (item.children && item.children.length > 0) {
      item.children.forEach(element => {
        if (element.meta && element.meta.isWhiteList) {
          arr.push(element.name)
        }
      })
    }
  })
  return arr
}

const vaildSec = 7 * 24 * 60 * 60 // 过期时间，一周 单位（秒）

const user = {
  state: {
    avatar: '', // TODO 动态头像
    defaultAvatar: 'http://b.resource.static.hzxinyule.com/xindong-1.png?imageView2/1/w/40/h/40',
    username: lget('username') || '',
    userShopId: '',
    token: getToken() || '',
    userLevel: null,
    sliderIsCollapse: lget('sliderIsCollapse') || false,
    // 记录跳转之前的页面查询参数
    routerParams: {
      $pageName: '' // 跳转之前的页面name
    },
    sliderMenu: lget('sliderMenu') || [],
    permissions: permissionRoutes, // 涉及到权限页面列表
    allPermissions: [], // 所有权限 设置权限 做展示
    // permissionsWhiteList: ['pms:order:detail', 'pms:goods:add', 'pms:goods:edit', 'pms:goods:evaluate'], // 权限白名单 允许页面通过、显示
    permissionsWhiteList: getWhiteList() || [], // 权限白名单 允许页面通过、显示
    userPermissions: lget('userPermissions') || [], // 登录用户拥有的权限页面列表
    // 页面板块头部的Nav list
    navPlateList: lget('loginUserPermission') || [],
    permissionTreeList: [],
    loginUserPermission: lget('loginUserPermission') || [],
    logistics: [] // 物流公司
  },
  mutations: {
    SET_USER_TOKEN: (state, data) => {
      state.token = data.tokenHead + ' ' + data.token
      window.$reqToken = state.token
      lset('token', state.token, vaildSec)
    },
    SET_USER_INFO: (state, data) => {
      state.username = data.nickName
      state.userShopId = data.shopId || 0
      state.avatar = data.icon ? data.icon : state.defaultAvatar
      lset('username', state.username, vaildSec)
    },
    REMOVE_USER: (state, data) => {
      state.username = ''
      state.avatar = ''
      lremoveall()
      lset('fullPath', data, vaildSec)
      lset('username', state.username, vaildSec)
    },
    SET_SLIDER_MENU: (state, data) => {
      let newSliderMenu = data
      // 前台设置sliderMenu
      // let newSliderMenu = []
      // permissionRoutes.forEach((item) => {
      //   if (item.meta.belong === data) {
      //     newSliderMenu.push(item)
      //   }
      // })
      state.sliderMenu = newSliderMenu
      lset('sliderMenu', state.sliderMenu, vaildSec)
    },
    SET_SLIDER_COLLAPSE: (state, data) => {
      state.sliderIsCollapse = data
      lset('sliderIsCollapse', data, vaildSec)
    },
    // 前台默认
    SET_USER_PERMISSIONS: (state, data) => {
      let menus = []
      // 前台路由设置权限
      permissionRoutes.forEach(item => {
        menus.push(item.name)
        if (item.children && item.children.length >= 1) {
          item.children.forEach(items => {
            menus.push(items.name)
          })
        }
      })
      menus = menus.concat(menus, state.permissionsWhiteList)
      state.userPermissions = menus
      lset('userPermissions', state.userPermissions, vaildSec)
    },
    // 记录上一页 查询参数
    SET_PAGE_ROUTER_PARAMS: (state, data) => {
      state.routerParams = data
    },
    // 对接后端接口
    SET_PERMISSIONS_TREE: (state, data) => {
      state.permissionTreeList = data
    },
    SET_LOGIN_USER_PERMISSIONS: (state, data) => {
      const loginUserPermission = data
      state.loginUserPermission = loginUserPermission
      lset('loginUserPermission', loginUserPermission, vaildSec)
      state.navPlateList = loginUserPermission
      // 设置路由权限 key
      let menus = []
      data.forEach(element => {
        menus.push(element.value)
        if (element.children && element.children.length >= 1) {
          element.children.forEach(item => {
            menus.push(item.value)
            if (item.children && item.children.length >= 1) {
              item.children.forEach(items => {
                menus.push(items.value)
              })
            }
          })
        }
      })
      menus = menus.concat(menus, state.permissionsWhiteList)
      state.userPermissions = menus
      lset('userPermissions', state.userPermissions, vaildSec)
      let IndexPath = ''
      if (loginUserPermission && loginUserPermission.length >= 1) {
        IndexPath = loginUserPermission[0].uri || '/pms/index'
        window.location.reload(IndexPath)
      } else {
        window.location.href = '/#/404'
      }
    },
    SET_LOGISTICS: (state, data) => {
      state.logistics = data
    }
  },
  actions: {
    login: ({
      commit
    }, data) => {
      commit('SET_USER_TOKEN', data)
    },
    loginout: ({
      commit
    }, data) => {
      commit('REMOVE_USER', data)
    },
    // 获取登录用户信息
    getLoginUserInfo: ({
      commit
    }, data) => {
      GetLoginUserInfo().then(res => {
        commit('SET_USER_INFO', res.data)
      })
    },
    // 设置slider数据
    setSliderMenu: ({
      commit
    }, data) => {
      commit('SET_SLIDER_MENU', data)
    },
    setUserPermissions: ({
      commit
    }, data) => {
      commit('SET_USER_PERMISSIONS', data)
    },
    // 折叠
    sliderCollapse: ({
      commit
    }, data) => {
      commit('SET_SLIDER_COLLAPSE', data)
    },
    // 保存查询参数
    setPageRouterParams: ({
      commit
    }, data) => {
      commit('SET_PAGE_ROUTER_PARAMS', data)
    },
    // 角色 保存权限树
    savePermissionTree: ({
      commit
    }, data) => {
      commit('SET_PERMISSIONS_TREE', data)
    },
    // 获取登录用户 权限
    getLoginUserPermissionList: ({
      commit
    }, data) => {
      GetLoginUserPermissionList().then(res => {
        const data = res.data
        commit('SET_LOGIN_USER_PERMISSIONS', data)
        commit('SET_SLIDER_MENU', data[0].children ? data[0].children : [])
      }).catch(() => {})
    },
    // 获取物流公司
    getLogistics: ({
      commit
    }, data) => {
      GetLogisticsList().then(res => {
        const data = res.data
        commit('SET_LOGISTICS', data)
      }).catch(() => {})
    }
  }
}

export default user
